package com.zero.ava.impl.kernel;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.MissingResourceException;

import com.zero.ava.kernel.ComponentRegistry;

/**
 * 组件管理器的基本实现
 * 
 * @author mac
 * 
 */
public class ComponentRegistryImpl implements ComponentRegistry {

	/**
	 * 存放组件
	 */
	private LinkedHashSet<Object> componentSet;

	ComponentRegistryImpl() {
		componentSet = new LinkedHashSet<Object>();
	}

	@Override
	public Iterator<Object> iterator() {
		return Collections.unmodifiableSet(componentSet).iterator();
	}

	@Override
	public <T> T getComponent(Class<T> type) {
		// 目标组件
		Object matchComponent = null;

		for (Object component : componentSet) {
			if (type.isAssignableFrom(component.getClass())) {
				if (matchComponent != null) {
					throw new MissingResourceException("More than one matching component", type.getName(), null);
				}
				matchComponent = component;
			}
		}

		if (matchComponent == null) {
			throw new MissingResourceException("No matching components", type.getName(), null);
		}

		return type.cast(matchComponent);
	}

	void addComponent(Object component) {
		componentSet.add(component);
	}

}
